package homework;

import java.util.Arrays;

//作业标题(2734)
//前序中序还原二叉树
//
//作业内容
//前序中序还原二叉树
//https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
public class h2734 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    private int nodePreIndex = 0;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return _buildTree(preorder, inorder, 0, inorder.length - 1);
    }
    private TreeNode _buildTree(int[] preorder, int[] inorder, int begin, int end)
    {
        if(begin > end) return null;
        TreeNode root = new TreeNode(preorder[nodePreIndex]);

        int rootIndex = __buildTree(inorder, begin, end, preorder[nodePreIndex]);
        if(rootIndex == -1) return null;
        nodePreIndex++;
        root.left = _buildTree(preorder, inorder, begin, rootIndex - 1);
        root.right = _buildTree(preorder, inorder, rootIndex + 1, end);
        return root;
    }

    private int __buildTree(int[] inorder, int begin, int end, int key)
    {
        for(int i = begin; i <= end; i++)
        {
            if(inorder[i] == key) return i;
        }
        return -1;
    }

}
